package dao.impl;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

import pojo.User;
import util.DBUtil;
import dao.UserDao;

public class UserDaoImpl implements UserDao {

	@Override
	public int addUser(User u) {
		String sql = "insert into users(id,name,password) values(user_id_seq.nextval,?,?)";
		Connection connection = null;
		PreparedStatement pst = null;
		int m=0;
		try {
			connection = DBUtil.createConnection();
			pst = connection.prepareStatement(sql);
			pst.setString(1, u.getName());
			pst.setString(2, u.getPassword());
			m=pst.executeUpdate();
			return 1;
		} catch (SQLException e) {
			e.printStackTrace();
			return 0;
		} finally{
			DBUtil.close(connection, pst, null);
		}
	}

	@Override
	public User loadUser(String name) {
		String sql = "select * from users where name=?";
		Connection connection = null;
		PreparedStatement pst = null;
		User user = null;
		try{
			connection = DBUtil.createConnection();
			pst = connection.prepareStatement(sql);
			pst.setString(1, name);
			ResultSet rs=pst.executeQuery();
			while(rs.next()){
				user = new User();
				user.setName(rs.getString("name"));
				user.setPassword(rs.getString("password"));
			}
			return user;
		} catch (SQLException e) {
			e.printStackTrace();
			return null;
		} finally{
			DBUtil.close(connection, pst, null);
		}
	}

	@Override
	public List<User> findAll() {
		List<User> list = new ArrayList<User>();
		
		String sql="select * from users";
		Connection connection = null;
		PreparedStatement pst=null;
		try {
			connection = DBUtil.createConnection();
			pst = connection.prepareStatement(sql);
			ResultSet rs = null;
			rs=pst.executeQuery();
			
			while(rs.next()){
				User user = new User();
				user.setName(rs.getString("name"));
				user.setPassword(rs.getString("password"));
				list.add(user);
			}
			return list;
		} catch (SQLException e) {
			e.printStackTrace();
			return list;
		} finally{
			DBUtil.close(connection, pst, null);
		}
	}

}
